import re
from idlelib.zoomheight import zoom_height

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import folium
from folium.plugins import HeatMap
import warnings

"""
******************
*参数区(请勿修改)*
******************
"""
# 关闭警告
warnings.filterwarnings(action='ignore')
# 绘图参数
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.sans-serif'] = ['SimHei']
# 高德地图参数
tile = 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
location = [31.1900, 121.4990]
attr = '高德-中英文对照'

"""
************
**项目准备**
************
"""

# 安装folium包（终端中运行）
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple folium

# 数据准备
# 打开"咖啡厅星巴克和瑞幸.xlsx"
data1 = pd.read_excel("咖啡厅星巴克和瑞幸.xlsx")
print(data1.head())
data2 = pd.read_excel("咖啡厅星巴克和瑞幸.xlsx", sheet_name="瑞幸")
print(data2.head())

"""
************
**数据清洗**
************
"""
"0. 去除空值"
data1 = data1.dropna()
data2 = data2.dropna()
# print(data1[data1['price'].isna()])
# print(data2[data2['price'].isna()])


"1. 价格转化为数值"
data1['price'] = data1['price'].map(lambda x: re.findall(r'¥(\d+)/人', x)[0]).astype(float)
# print(data1.head())
data2['price'] = data2['price'].map(lambda x: re.findall(r'¥(\d+)/人', x)[0]).astype(float)
# print(data2.head())
"2. 评分转化为数值"
data1["flavor"] = data1['score'].map(
    lambda x: re.findall(r'口味:(\d+.\d+) 环境:(\d+.\d+) 服务:(\d+.\d+)', x)[0][0]).astype(float)
data1["env"] = data1['score'].map(
    lambda x: re.findall(r'口味:(\d+.\d+) 环境:(\d+.\d+) 服务:(\d+.\d+)', x)[0][1]).astype(float)
data1["service"] = data1['score'].map(
    lambda x: re.findall(r'口味:(\d+.\d+) 环境:(\d+.\d+) 服务:(\d+.\d+)', x)[0][2]).astype(float)
data2["flavor"] = data2['score'].map(
    lambda x: re.findall(r'口味:(\d+.\d+) 环境:(\d+.\d+) 服务:(\d+.\d+)', x)[0][0]).astype(float)
data2["env"] = data2['score'].map(
    lambda x: re.findall(r'口味:(\d+.\d+) 环境:(\d+.\d+) 服务:(\d+.\d+)', x)[0][1]).astype(float)
data2["service"] = data2['score'].map(
    lambda x: re.findall(r'口味:(\d+.\d+) 环境:(\d+.\d+) 服务:(\d+.\d+)', x)[0][2]).astype(float)
print(data2.head())
"3. 经纬度分离"
data1['lat'] = data1['poi'].map(lambda x: eval(x)['lat'])
data1['lng'] = data1['poi'].map(lambda x: eval(x)['lng'])
# print(data1.head())
data2['lat'] = data2['poi'].map(lambda x: eval(x)['lat'])
data2['lng'] = data2['poi'].map(lambda x: eval(x)['lng'])
# print(data2.head())

"""
************
**数据分析**
************
"""
"1. 价格对比"
## 分析项目
# 平均值
# 最大值
# 最小值
"**统计计算**"
# 三种统计量
data1_mean = data1['price'].mean()
data1_max = data1['price'].max()
data1_min = data1['price'].min()
data2_mean = data2['price'].mean()
data2_max = data2['price'].max()
data2_min = data2['price'].min()
# 横坐标
x1 = [x - 0.1 for x in range(3)]
x2 = [x + 0.1 for x in range(3)]
"**可视化**"
# 条形图
plt.bar(x1, [data1_mean, data1_max, data1_min], width=0.2, label="星巴克")
plt.bar(x2, [data2_mean, data2_max, data2_min], width=0.2, label="瑞幸")
plt.legend()
plt.ylabel('元/人')
plt.xticks(range(3), ['平均值', '最大值', '最小值'])
plt.show()
"##################################################"

"2. 评论分布"
## 分析项目
# 评论数分布
"**统计计算**"
# 总体情况
print(data1['review_count'].describe())
print(data2['review_count'].describe())

"**可视化**"
# 直方图
plt.subplot(121)
plt.hist(data1['review_count'], bins=range(0,500,50))
plt.title('星巴克评论数发布')
plt.subplot(122)
plt.hist(data2['review_count'], bins=range(0,500,50))
plt.title('瑞幸评论数发布')
plt.show()
"##################################################"

"3. 评分对比"
## 分析项目
# 平均星级、口味、环境、服务对比
"**可视化**"
# 箱线图
plt.figure(figsize=(10,10))
plt.subplot(221)
plt.boxplot([data1['stars'],data2['stars']])
plt.xticks([1,2],['星巴克','瑞幸'])
plt.title('星级')

plt.subplot(222)
plt.boxplot([data1['flavor'],data2['flavor']])
plt.xticks([1,2],['星巴克','瑞幸'])
plt.title('口味')

plt.subplot(223)
plt.boxplot([data1['env'],data2['env']])
plt.xticks([1,2],['星巴克','瑞幸'])
plt.title('环境')

plt.subplot(224)
plt.boxplot([data1['service'],data2['service']])
plt.xticks([1,2],['星巴克','瑞幸'])
plt.title('服务')
plt.show()
"##################################################"

"4. 门店数量对比"
## 分析项目
# 整体门店数量对比（总数、覆盖城市数）
# 市场占有率(共有城市)
"**统计计算**"
# 门店总数
data1_sum=data1['name'].count()
data2_sum=data2['name'].count()
# 覆盖城市数
data1_city=len(data1.groupby('cityname'))
data2_city=len(data2.groupby('cityname'))
# 过滤共有城市数据
data1_common=data1[data1['cityname'].isin(data2['cityname'])]
data1_common['brand']='星巴克'
data2_common=data2[data2['cityname'].isin(data1['cityname'])]
data2_common['brand']='瑞幸'
common=pd.concat([data1_common,data2_common])
common_sum=common.groupby('brand')['name'].count()
# 横坐标
x1=[x - 0.1 for x in range(1)]
x2=[x + 0.1 for x in range(1)]
"**可视化**"
# 条形图
plt.subplot(221)
plt.bar(x1,data1_sum,width=0.2,label='星巴克')
plt.bar(x2,data2_sum,width=0.2,label='瑞幸')
plt.title('门店总数')
plt.legend()
plt.subplot(222)
plt.bar(x1,data1_city,width=0.2,label='星巴克')
plt.bar(x2,data2_city,width=0.2,label='瑞幸')
plt.title('覆盖城市数')
plt.legend()

# 饼状图
plt.subplot(212)
plt.pie(common_sum,autopct='%.2f%%',labels=['星巴克','瑞幸'])
plt.title('市场占有率')
plt.legend()
plt.show()
"##################################################"

"5. 地理位置(以上海为例)对比"
"**统计计算**"
# 过滤上海数据
data1_sh=data1[data1['cityname']=='上海市']
data2_sh=data2[data2['cityname']=='上海市']
# 将经纬度合并为列表
data1_loc=[[row['lng'],row['lat']] for name,row in data1_sh.iterrows()]
data2_loc=[[row['lng'],row['lat']] for name,row in data2_sh.iterrows()]
"**可视化**"
# 热力图
data1_heatmap=folium.Map(location=location,tiles=tile,attr=attr,zoom_start=10)
data1_heatmap.add_child(HeatMap(data1_loc))
data1_heatmap.save('星巴克热力图.html')

data2_heatmap=folium.Map(location=location,tiles=tile,attr=attr,zoom_start=10)
data2_heatmap.add_child(HeatMap(data2_loc))
data2_heatmap.save('瑞幸热力图.html')
"#################################################"